package com.iflytek.aidemo.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.iflytek.aidemo.model.User;

/**
 * 用户会话管理类
 */
public class SessionManager {
    private static final String PREF_NAME = "UserSession";
    private static final String KEY_USER_ID = "user_id";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_USER_TYPE="usertype";
    private static final String KEY_IS_LOGGED_IN = "is_logged_in";

    
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private Context context;
    
    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }
    
    /**
     * 保存用户登录信息
     */
    public void saveUserSession(User user) {
        editor.putString(KEY_USER_ID, user.getUserId());
        editor.putString(KEY_USERNAME, user.getUserName());
        editor.putString(KEY_USER_TYPE, user.getUserType());
        editor.putBoolean(KEY_IS_LOGGED_IN, true);
        editor.apply();
    }
    
    /**
     * 获取当前登录用户信息
     */
    public User getCurrentUser() {
        if (!isLoggedIn()) {
            return null;
        }
        
        User user = new User();
        user.setId(sharedPreferences.getString(KEY_USER_ID, ""));
        user.setUserName(sharedPreferences.getString(KEY_USERNAME, ""));
        user.setUserType(sharedPreferences.getString(KEY_USER_TYPE, ""));
        
        return user;
    }
    
    /**
     * 检查用户是否已登录
     */
    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }
    
    /**
     * 获取用户Token
     */
    
    /**
     * 获取用户名
     */
    public String getUsername() {
        return sharedPreferences.getString(KEY_USERNAME, "");
    }
    
    /**
     * 清除用户会话
     */
    public void clearSession() {
        editor.clear();
        editor.apply();
    }
    
    /**
     * 更新用户信息
     */
    public void updateUserInfo(User user) {
        if (user.getUserName() != null) {
            editor.putString(KEY_USERNAME, user.getUserName());
        }
        if (user.getUserType() != null) {
            editor.putString(KEY_USER_TYPE, user.getUserType());
        }
        editor.apply();
    }
} 